  <template>
	<div class="newEnjoy-20180410 mescroll" id="mescroll">
		<header class="head">
			<img src="~@/assets/imgs/20180410/xryx_head1.jpg" />
			<img src="~@/assets/imgs/20180410/xryx_head2.jpg" />
			<div class="flex flex-item-center btn-position"><button class="btn" ref="getBtn" @click="getTicket">一键领取</button></div>
			<div class="fix-save-img"></div>
		</header>
		<main class="content">
			<header>
				<img src="~@/assets/imgs/20180410/xryx_first_order.png" />
				<div class="fix-save-img"></div>
			</header>
			<div class="menu-wrap">
				<v-touch class="menu-list cancel-touch-action" id="menu-list" @pan="switchTab($event)" @tap="switchTab($event)">
					<a tag="a" href="javascript:void(0)" :data-id="groupIds[0]" data-key="1" class="cur">为你精选</a>
					<a tag="a" href="javascript:void(0)" :data-id="groupIds[1]" data-key="2">精致美妆</a>
					<a tag="a" href="javascript:void(0)" :data-id="groupIds[2]" data-key="3">母婴优选</a>
					<a tag="a" href="javascript:void(0)" :data-id="groupIds[3]" data-key="4">品质家电</a>
					<a tag="a" href="javascript:void(0)" :data-id="groupIds[4]" data-key="5">钟爱一生</a>
					<a tag="a" href="javascript:void(0)" :data-id="groupIds[5]" data-key="6">爆款手机</a>
				</v-touch>
			</div>
			<ul class="goods-list" id="dataList" v-cloak>
				<li v-for="item in pdlist" @click="goActivityGoods(item.id)">
					<span class="pic flex flex-item-center"><img :src="item.attaUrl" /></span>
					<div class="info">
						<h1 class="ecs ecs-2">{{item.goodsName}}</h1>
						<span class="monthly"><em>月供</em><sub>￥</sub><sup>{{item.installmentAmount/100}}</sup></span>
						<span class="money">￥{{(item.price/100).toFixed(2)}}</span>
						<button v-if="groupId==groupIds[0] && item.price>10*100"><span class="ticket">用券立减10元</span></button>
						<button v-if="groupId==groupIds[1] && item.price>100*100"><span class="ticket">用券立减50元</span></button>
						<button v-if="groupId==groupIds[2] && item.price>100*100"><span class="ticket">用券立减20元</span></button>
						<button v-if="groupId==groupIds[3] && item.price>500*100"><span class="ticket">用券立减50元</span></button>
						<button v-if="groupId==groupIds[4] && item.price>800*100"><span class="ticket">用券立减70元</span></button>
						<button v-if="groupId==groupIds[5] && item.price>4000*100"><span class="ticket">用券立减100元</span></button>
					</div>
				</li>
			</ul>
		</main>
		<go-home></go-home>
	</div>
</template>
<script>
	import Utils from '@/util/util';
	import MeScroll from 'mescroll';
	import Api from '@/util/api';
	import GoHome from '@/components/goHome';
	import "mescroll/src/mescroll.min.css";

	export default {
		name: 'activity20180410',
		components: {
	      'go-home': GoHome
	    },
		data() {
			let self = this;
			return {
				token: '',
				mescroll: null,
				pdlist: [],
				groupId: 30,
				groupIds: [ 30, 26, 31, 27, 29, 28 ],
				activeId: 8,
				curIndex: 1,
				curScrollLeft: 0,
				oldUser: false,
				animateRight: null,
				animateLeft: null,
				timer: null,
				num: 1,
				size: 10,
				flag: false,
			}
		},
		created(){
	      let self = this;
	      document.title = '新人优享';
//	      this.otoData = this.__proto__.__proto__.dataBind;
//		  if(this.$route.query['t'].split("=")[1]) this.token = this.$route.query['t'].split("=")[1];
	      window.loginCallBack = (token)=>{
		     self.token = token;
		     token && self.isGetTicket();
		  }

	    },
		mounted() {
			//创建MeScroll对象,down可以不用配置,因为内部已默认开启下拉刷新,重置列表数据为第一页
			//解析: 下拉回调默认调用mescroll.resetUpScroll(); 而resetUpScroll会将page.num=1,再执行up.callback,从而实现刷新列表数据为第一页;
			var self = this;
			self.isGetTicket();
			self.mescroll = new MeScroll("mescroll", { //请至少在vue的mounted生命周期初始化mescroll,以确保您配置的id能够被找到
				up: {
					callback: self.upCallback, //上拉回调
					//以下参数可删除,不配置
					isBounce: true, //此处禁止ios回弹,解析(务必认真阅读,特别是最后一点): http://www.mescroll.com/qa.html#q10
					page:{
						num: 1,
						size:10,
						time: null
					}, //可配置每页8条数据,默认10
					toTop:{ //配置回到顶部按钮
						src : require("../../../assets/imgs/mescroll-totop.png"), //默认滚动到1000px显示,可配置offset修改
						//html: null, //html标签内容,默认null; 如果同时设置了src,则优先取src
						//offset : 1000
					},
					offset: 100,
					empty:{ //配置列表无任何数据的提示
						warpId:"dataList",
						icon : require("../../../assets/imgs/mescroll-empty.png"), 
						tip : "亲,暂无相关数据哦~" , 
	//						  	btntext : "去逛逛 >" , 
	//						  	btnClick : function() {
	//						  		alert("点击了去逛逛按钮");
	//						  	} 
					},
					showLoading: function(mescroll) {
						//console.log("yilei");
					},
					scrollbar: {
						use: false
					}
				},
				down: {
					use: false
				}
			});
			self.upCallback({num: 1, size: 10})
		},
	    methods: {
	    	isGetTicket(fromBtn, callback){
	    		let token = sessionStorage.getItem("plus_token") || Utils.getQueryString("token") || this.token, self = this;
	    		if(token && token != 'null') {
	    			const res = this.post(Api.validateNewUserByActivity, {activeId: self.activeId}, {token});
	    			res.then(res=>{
	    				//初次加载时判断是否领取
	    				if(res.data.validateGrabedCoupon && !fromBtn) {
    						this.$refs.getBtn.innerText = '已领取';
    						this.$refs.getBtn.disabled = true;
    						this.$refs.getBtn.style.cssText = 'opacity: .3';
    						return;
    					}

    					//如果是来自按钮触发
    					if(res.data.validateOldUser) {
    						this.$vux.toast.show({type: 'text', text: '此活动仅限花伴商城新人参加，花伴为您准备了更多好礼', time: 3000, position: 'middle'});
    						self.oldUser = true;
    						setTimeout(()=>{ Utils.goHome(); }, 2400)
    					}else {
    						self.oldUser = false;
    						callback();
    					}
	    			})
	    		}
	    	},
	    	getTicket() {
	    		let dom = this.$refs.getBtn, token = sessionStorage.getItem("plus_token") || Utils.getQueryString("token") || this.token, self = this;


	    		if(!token || token == 'null') {

	    			if(Utils.isNativeApp() || Utils.isWxPlus()){
		    			token = Utils.getUserToken();
		    			this.token = token;
		    		}

		    		if(Utils.isWxPlus() && !token || token == 'null') {
		    			token = sessionStorage.getItem("plus_token") || Utils.getQueryString("token");
		    		}

				    if(!token || token == 'null') {
				    	window.parent.postMessage({type: 'login', callback: 'http://192.168.1.113:8080/#/newEnjoy?isDebug=true'}, '*');
				    	return;
				    }
	    		}

	    		this.isGetTicket(true, ()=>{
		    		dom.setAttribute('disabled','disabled');
		    		this.$vux.loading.show();
		    		const res = this.post(Api.couponGrabCoupons, {activeId: self.activeId}, {token});
		    		res.then(data => {
		    			if (data.code == '200') {
							dom.innerText = '已领取';
							this.$vux.toast.text('领券成功!', 'middle');
				    	} else {
							if(data.message == "非常抱歉，您已经在该活动中领取了优惠券，不能重复领取！"){
								dom.innerText = '已领取';
							}else {
								dom.removeAttribute('disabled');
							}
							if(data.code !== 1011){
								this.$vux.toast.text(data.message, 'middle');
							}
				    	}
				    	this.$vux.loading.hide();
				    	dom.style.cssText = 'opacity: .3';

		    		}).catch(function (error) {//加上catch
			          console.log(error);
			        })
	    		});
	    	},
	    	goActivityGoods: function(goodsId) {
				let self = this;
	    		if(this.flag) return;
	    		this.flag = true;
	    		Utils.goGoods(goodsId);
				setTimeout(()=>{ self.flag = false }, 1000);
			},
			startMove(domChild, direction, ii){
				let self = this, 
				parent = domChild.parentNode, 
				curScrollLeft = parent.scrollLeft, 
				calcScrollWidth = parent.scrollWidth - parent.clientWidth, 
				left = 0, 
				iTarget = direction == 'right'? calcScrollWidth > curScrollLeft+domChild.clientWidth? curScrollLeft + domChild.clientWidth + 10 : calcScrollWidth : curScrollLeft - domChild.clientWidth > 0? curScrollLeft - domChild.clientWidth + 10 : 0, step, cur = curScrollLeft;
				//iTarget = ii == '6'? curScrollLeft : ii == '1'? 0 : iTarget;
				 self.timer = setInterval(function(){
					 //更新当前值
			        cur = parent.scrollLeft;
			        
			        step = 10;

			        //若步长设置值使得元素超过目标点时，将步长设置值更改为目标点值 - 当前值
			        if(direction == 'right' && (cur + step - iTarget)*step > 0) {
			        	step = iTarget - cur;
			        }

			        if(direction == 'left' && (cur + step - iTarget)*step < 0) {
			        	step = iTarget - cur;
			        }
			        //将合适的步长值赋值给元素的样式
			        parent.scrollLeft = direction == 'right'? (cur + step) : (cur - step);

			        //当元素到达目标点时，停止定时器
			        if(step == iTarget - cur){
			            clearInterval(self.timer);
			            self.timer = 0;
			            //parent.className = 'menu-list';
			            //fn && fn.call(obj);    
			        }    
				 }, 10);
				 
			},
			moveRight(ii, domChild) {
				let parent = domChild.parentNode, curScrollLeft = parent.scrollLeft, self = this;
				
				this.animateRight = setInterval(()=>{
					parent.scrollLeft++;
					if(ii != 6) {
						if(parent.scrollLeft >= curScrollLeft + domChild.clientWidth + 10) {
							clearInterval(self.animateRight);
							self.animateRight = null;
						}
					}else {
						if(parent.scrollLeft == curScrollLeft) {
							clearInterval(self.animateRight);
							self.animateRight = null;
						}
					}
				}, 1000/120)
			},
			moveLeft(ii, domChild) {
				let parent = domChild.parentNode, curScrollLeft = parent.scrollLeft, self = this;

				this.animateLeft = setInterval(()=>{
					parent.scrollLeft--;
					if(ii != 1) {
						if(parent.scrollLeft <= curScrollLeft - domChild.clientWidth - 10) {
							clearInterval(self.animateLeft);
							self.animateLeft = null;
						}
					}else {
						if(parent.scrollLeft == 0) {
							clearInterval(self.animateLeft);
							self.animateLeft = null;
						}
					}
				}, 1000/120);
			},
			//上拉回调 page = {num:1, size:10}; num:当前页 ,默认从1开始; size:每页数据条数,默认10
			upCallback: function(page) {
				//联网加载数据
				var self = this;
				self.getListDataFromNet(page.num, page.size, function(curPageData, totalSize) {

					//如果是第一页需手动制空列表 (代替clearId和clearEmptyId的配置)
					if(page.num == 1) self.pdlist = [];
					
					//更新列表数据
					//self.pdlist = self.pdlist.concat(curPageData);

					self.$set(self.$data, 'pdlist', self.pdlist.concat(curPageData))
					
					self.mescroll.endSuccess(curPageData.length, totalSize > page.size*page.num);
				
				}, function() {
					//联网失败的回调,隐藏下拉刷新和上拉加载的状态;
					self.mescroll.endErr();
				});
			},
			getListDataFromNet(pageNum,pageSize,successCallback,errorCallback) {
				let self = this;
				//延时一秒,模拟联网
				const res = this.post(Api.queryGroupGoods, {"groupId": self.groupId, "numPerPage": pageSize, "order": "asc", "pageNum": pageNum});
	            res.then(res=>{
	            	successCallback(res.data.rows, res.data.total);
	            })
			},
			switchTab(e) {
				clearInterval(this.timer);
				this.timer = null;

				if(e.type == 'tap') {
					let parent = e.target.parentNode, curLeft = parent.scrollLeft;
					if(!e.target.getAttribute("data-id")) return;
					for(var element of parent.children) { element.className = '';}
					e.target.className = 'cur';

					this.curScrollLeft = parent.scrollLeft;

					if(parent.clientWidth - e.changedPointers[0].clientX < e.target.clientWidth && parseInt(e.target.getAttribute("data-key")) > parseInt(this.curIndex)) {
						//this.moveRight(e.target.getAttribute("data-key"), e.target);
						this.startMove(e.target, 'right', e.target.getAttribute("data-key"));
					}

					if(e.changedPointers[0].clientX < e.target.clientWidth && parseInt(e.target.getAttribute("data-key")) < parseInt(this.curIndex)) {
						//this.moveLeft(e.target.getAttribute("data-key"), e.target);
						this.startMove(e.target, 'left', e.target.getAttribute("data-key"));
					}
					
					this.groupId = e.target.getAttribute("data-id");
					this.curIndex = e.target.getAttribute("data-key");
					this.mescroll.options.up.page.num = 1;
					this.upCallback({num: 1, size: 10})
				}

			}
		},
	}
</script>
<style lang='less' scoped="scoped">
	@import '~@/assets/less/main.less';

	/*vue*/
	[v-cloak] {
	  display: none;
	}

	.newEnjoy-20180410 {
		background: #ffe462;
		-webkit-tap-highlight-color:transparent;
		&.mescroll {
			position:fixed;
			top:0;
			left: 0;
			width: 100%;
			height:100%;
		}
		.head {
			position: relative;
			img {
				display: block;
				width: 100%;
			}
			.btn-position{
				position: absolute;
				width: 100%;
				bottom: .3rem;
				z-index: 2;
				button.btn {
					width: 5.16rem;
					height: .62rem;
					background: url("~@/assets/imgs/20180410/xryx_get.png") no-repeat;
					background-size: 100% auto;
					border: none;
					padding: 0;
					font-size: .3rem;
					color: #fff;
					outline: none;
				}
			}
		}
		.content {
			overflow-y: hidden;
			header {
				position: relative;
				img {
					width: 100%;
					display: block;
				}
			}
			.menu-wrap {
				height: .95rem;
				line-height: .95rem;
				padding: 0 .2rem;
				overflow:hidden;
				background: #fff;
			}
			.menu-list {
				white-space: nowrap;
				overflow-x: scroll;
				-ms-overflow-style: none;
				overflow: -moz-scrollbars-none;
				&.cancel-touch-action {
					touch-action: manipulation!important;
				}
				&::-webkit-scrollbar { width: 0 !important }

				//transition: margin 1s;
				a {
					display: inline-block;
					padding: 0 .2rem;
					height: .66rem;
					text-align: center;
					line-height: .66rem;
					color: #421a03;
					text-decoration: none;
					border-radius: .08rem;
					user-select: none;
					&.cur {
						background: #ff794a;
						color: #fff;
						box-shadow: 0 .03rem .03rem #ff794a;
					}
				}
			}
			.goods-list {
				margin: .15rem .2rem .2rem;
				overflow: hidden;
				li {
					width: 3.44rem;
					height: 6.25rem;
					border-radius: .08rem;
					background: #fff;
					margin-bottom: .2rem;
					padding-bottom: .2rem;
					touch-action: manipulation;
					&:nth-child(odd) {
						float: left;
						clear: both;
					}
					&:nth-child(even) {
						float: right;
					}
					.pic {
						height: 3.68rem;
						border-bottom: .01rem solid #e4e4e4;
						img {
							display: block;
							width: 80%;
						}
					}
					.info {
						padding: 0 .2rem;
						h1 {
							font-size: .3rem;
							line-height: .4rem;
							margin: .1rem 0;
							height: .8rem;
							padding: 0;
							overflow: hidden;
						}
						.monthly {
							display: block;
							em {
								font-style: normal;
								font-size: .24rem;
							}
							sub {
								font-size: .24rem;
								line-height: .24rem;
							}
							sub, sup {
								vertical-align: 0;
								color: #ff457e;
							}
							sup {
								font-size: .36rem;
								line-height: .36rem;
							}
						}
						.money {
							font-size: .2rem;
							color: rgba(0,0,0,0.4);
						}
						button {
							background-color: #ff457e;
							border: none;
							width: 3rem;
							height: .6rem;
							border-radius: .1rem;
							padding: 0;
							margin-top: .1rem;
							text-align: left;
							outline: none;
							span.ticket {
								font-size: .3rem;
								color:#fff;
								margin-left: .3rem;
							}
							background-image: url("~@/assets/imgs/20180410/xryx_list_icon.png");
							background-repeat: no-repeat;
							background-size: .29rem .29rem;
							background-position: 2.5rem center;
						}
					}
				}
			}
		}
		.mescroll-upwarp{
			padding: 0 0 .3rem;
			height: 1rem;
		}
	}
</style>